package com.chuanwei.filter;

import com.chuanwei.utils.CurrentHolder;
import com.chuanwei.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Map;

@WebFilter(urlPatterns = "/*")
@Slf4j
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //1.获取到请求路径
        String path = request.getRequestURI();//  /login

        //2.判断是否是登录请求，如果路径中包含/login，说明是登录请求 ， 则放行
        if (path.contains("/login")){
            log.info("登录请求 ，放行");
            filterChain.doFilter(request,response);
            return; //放行完事之后此方法结束了
        }

        //3.如果路径中不包含/login，获取到token
        String token = request.getHeader("token");

        //4.判断token是否存在，如果不存在，说明用户没有登录，返回错误信息（响应401状态码）
        if (token == null || token.isEmpty()){
            log.info("令牌为空，响应401状态码");
            response.setStatus(401);
            return;
        }

        //5.如果token存在，校验令牌是否正确，如果错误，则返回错误信息（响应401状态码）
        try {
            Map<String, Object> claims = JwtUtils.parseJwt(token);
            Integer empId  = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empId);//存入
            log.info("当前登录员工id：{}，将其存入ThreadLocal",empId);

        } catch (Exception e) {
            log.info("令牌非法，响应401状态码");
            response.setStatus(401);
            return;
        }

        //6.如果校验通过，则放行
        log.info("令牌合法，放行");
        filterChain.doFilter(request,response);

        //7.在当前线程中移除当前登录员工id（删除ThreadLocal中的数据）资源放行完毕还会执行过滤器后面的逻辑
        CurrentHolder.remove();
    }
}
